package com.bsd.xxyp.rdlock.config;

import com.bsd.xxyp.rdlock.context.LockHolder;
import com.bsd.xxyp.rdlock.executor.RedissonLockExecutor;
import com.bsd.xxyp.rdlock.executor.ZkCuratorLockExecutor;
import com.bsd.xxyp.rdlock.handler.RdLockHandler;
import com.bsd.xxyp.rdlock.parse.DefaultLockKeyProcessor;
import com.bsd.xxyp.rdlock.parse.LockKeyProcessor;
import com.bsd.xxyp.rdlock.executor.JedisLockExecutor;
import com.bsd.xxyp.rdlock.executor.LockExecutor;
import org.apache.curator.framework.CuratorFramework;
import org.redisson.api.RedissonClient;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.*;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.*;
import org.springframework.core.Ordered;
import redis.clients.jedis.JedisCluster;

import java.util.List;

/**
 * @author ：wangcheng
 * @date 2022/12/13
 **/
@Configuration
@EnableConfigurationProperties(RdLockProperties.class)
@ConditionalOnProperty(prefix = "bsd.xxxp.lock",name = "enable",havingValue = "true",matchIfMissing = true)
@AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE)
public class RdLockAutoConfiguration  {

    @Bean
    @ConditionalOnMissingBean
    public LockKeyProcessor lockKeyProcessor(LockHolder lockHolder){
        return new DefaultLockKeyProcessor(lockHolder);
    }

    @Bean
    @ConditionalOnBean(JedisCluster.class)
    public JedisLockExecutor jedisLockExecutor(JedisCluster jedisCluster) {
        return new JedisLockExecutor(jedisCluster);
    }

    @Bean
    @ConditionalOnBean(RedissonClient.class)
    public RedissonLockExecutor redissonLockExecutor(RedissonClient redissonClient) {
        return new RedissonLockExecutor(redissonClient);
    }

    @Bean
    @ConditionalOnBean(CuratorFramework.class)
    public ZkCuratorLockExecutor zkCuratorLockExecutor(CuratorFramework curatorFramework) {
        return new ZkCuratorLockExecutor(curatorFramework);
    }

    @Bean
    public LockHolder lockHolder(List<LockExecutor> lockExecutors,RdLockProperties properties) {
        return new LockHolder(lockExecutors,properties);
    }

    @Bean
    public RdLockHandler rdLockHandler(LockHolder lockHolder,LockKeyProcessor lockKeyProcessor) {
        return new RdLockHandler(lockHolder,lockKeyProcessor);
    }

}
